package nl.dxn.tunnel.server.proxy;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.flush.FlushConsolidationHandler;
import io.netty.handler.ipfilter.RuleBasedIpFilter;
import nl.dxn.tunnel.server.config.TcpConfigProperties;
import nl.dxn.tunnel.server.handel.ClientTcpHandler;
import nl.dxn.tunnel.server.ip.IpFilterRuleHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpServer{
    private static final Logger logger = LoggerFactory.getLogger(TcpServer.class);

    private final ServerBootstrap bootstrap = new ServerBootstrap();
    private final NioEventLoopGroup serverBossGroup = new NioEventLoopGroup();
    private final NioEventLoopGroup serverWorkerGroup = new NioEventLoopGroup();

    private TcpConfigProperties tcpProperties;

    public TcpServer(final TcpConfigProperties tcpProperties) {
        this.tcpProperties = tcpProperties;
        bootstrap.group(serverBossGroup, serverWorkerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new RuleBasedIpFilter(new IpFilterRuleHandler()));
                        ch.pipeline().addLast(new ChannelDuplexHandler());
                        ch.pipeline().addLast(new FlushConsolidationHandler(5));
                        // 代理客户端连接代理服务器处理器
                        ch.pipeline().addLast(new ClientTcpHandler(tcpProperties));
                    }
                });
    }

    public void destroy() throws Exception {
        serverBossGroup.shutdownGracefully();
        serverWorkerGroup.shutdownGracefully();
    }

    public boolean run() throws Exception {
        //启动服务器并绑定一个端口并且同步生成一个 ChannelFuture 对象
        ChannelFuture cf = bootstrap.bind(tcpProperties.getPort()).sync();
        if (cf.isSuccess()) {
            logger.info("tcp服务端启动成功,本机绑定IP:{},tcp端口:{}", tcpProperties.getIp(), tcpProperties.getPort());
            return true;
        } else {
            logger.info("tcp服务端启动失败,本机绑定IP:{},tcp端口:{},原因:{}"
                    , tcpProperties.getIp(), tcpProperties.getPort(), cf.cause().getMessage());
            this.destroy();
            return false;
        }
    }
}
